use clap::Parser;
use image_compress::{image_compress, is_image};
use std::path::Path;
use std::{fs, thread};

#[derive(Parser, Debug, Default)]
#[command(version="1.0.0", about="about", long_about = None)]
struct Args {
    /// Input image file path
    #[arg(required = true)]
    input: String,

    /// Output image file path
    #[arg(default_value = "")]
    output: String,

    /// Compression quality (1 to 100)
    #[arg(default_value_t = 50)]
    quality: i32,
}

fn main() {
    let args = Args::parse();
    let input_path = Path::new(&args.input);

    if input_path.is_dir() {
        for entry in fs::read_dir(input_path).unwrap() {
            let entry = entry.unwrap();
            let input_path = entry.path();

            // 检查文件扩展名是否是图片格式
            if is_image(&input_path) {
                let file_stem = input_path.file_stem().unwrap_or_default();
                let extension = input_path.extension().unwrap_or_default();

                let folder = if args.output.is_empty() {
                    Path::new(&args.input)
                } else {
                    Path::new(&args.output)
                };

                if !folder.exists() {
                    fs::create_dir_all(folder).expect("文件夹创建失败");
                }

                let out_path = Path::join(
                    folder,
                    format!(
                        "{}_compress.{}",
                        file_stem.to_string_lossy(),
                        extension.to_string_lossy()
                    ),
                );

                let quality = args.quality;

                let handle = thread::spawn(move || {
                    let _ = match image_compress(
                        Box::new(input_path.as_path()),
                        Box::new(out_path.as_path()),
                        quality,
                    ) {
                        Ok(_) => println!("压缩成功:: {}", out_path.as_path().display()),
                        Err(e) => println!("Error: {}", e),
                    };
                });
                handle.join().unwrap();
            }
        }
    } else {
        let folder_path = input_path.parent().unwrap();
        if !folder_path.exists() {
            fs::create_dir_all(folder_path).expect("文件夹创建失败");
        }
        let out_path = if args.output.is_empty() {
            let input_path = Path::new(&input_path);

            let file_stem = input_path.file_stem().unwrap_or_default();
            let extension = input_path.extension().unwrap_or_default();

            Path::join(
                folder_path,
                format!(
                    "{}_compress.{}",
                    file_stem.to_string_lossy(),
                    extension.to_string_lossy()
                ),
            )
        } else {
            Path::new(&args.output).to_path_buf()
        };

        let out_path = out_path.as_path();

        let quality = args.quality;

        let _ = match image_compress(Box::new(input_path), Box::new(out_path), quality) {
            Ok(_) => println!("压缩成功:: {}", out_path.display()),
            Err(e) => println!("Error: {}", e),
        };
    }
}
